package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"encoding/json"
	"time"
	"strconv"
	"os/exec"
	"log"
)

func main() {
	gin.SetMode(gin.ReleaseMode)
	en :=gin.Default()
	en.POST("/",hookHandle)
	http.ListenAndServe(":9999",en)
}

func hookHandle ( c *gin.Context){
	body,_ :=c.GetRawData()
	var webData WebHookData
	json.Unmarshal(body,&webData)
	nowTime := time.Now().Format("20060102-15:04:05")
	nowTime = nowTime+"-"+strconv.FormatInt(time.Now().Unix(),10)+".log"
	log.Printf("%s\t%s\t%s ","sh",webData.Repository.FullName+".sh",">"+nowTime)
	cmd := exec.Command("/bin/sh","-c",`sh `+webData.Repository.FullName+".sh"+` >`+nowTime)
	err :=  cmd.Run()
	if err !=nil {
		log.Println(err)
	}
	// cmd.Wait()
}

type WebHookData struct {
	HookName string `json:"hook_name"`
	Ref string			`json:"ref"`
	Repository Repository `json:"repository"`
}

type Repository struct {
	Id int			`json:"id"`
	Name string		`json:"name"`
	Path string		`json:"path"`
	FullName string	`json:"full_name"`
	GitSshUrl string `json:"git_ssh_url"`
}

